package jmine.tec.test.integration;

import static junit.framework.Assert.fail;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;

import bancosys.tec.utils.reader.URLReaderFactory;

/**
 * Class to test the spreadsheets that have the sheet of Documentation (quality)
 * 
 * @author Willian Gigliotti
 */
public abstract class AbstractCommentsTestCase {

    private String documentationSheet = "NExec_@Doc";

    /**
     * Executes the tests
     * 
     * @throws IOException if occurs errors reading the archives.
     */
    @Test
    public void executeTest() throws IOException {
        for (String path : this.getDirectories()) {
            this.doTests(path);
        }
    }

    /**
     * This method must return a list of the directories, that will be tested.
     * 
     * @return paths containing integration tests
     */
    protected abstract String[] getDirectories();

    /**
     * Executes a test to verify if the .xls archives have comments.
     * 
     * @param pathFile folder
     * @throws IOException if occurs errors in the tests.
     */
    protected void doTests(String pathFile) throws IOException {
        List<URL> files = this.getFiles(pathFile);
        int spreadsheetsWithoutComments = 0;
        StringBuilder arquivosErrados = new StringBuilder();

        for (URL file : files) {
            if (!this.hasComments(file)) {
                spreadsheetsWithoutComments++;
                String[] path = file.getPath().split(pathFile);
                arquivosErrados.append(pathFile + path[path.length - 1] + "\n ");
            }
        }

        if (spreadsheetsWithoutComments > 0) {
            fail("There are " + spreadsheetsWithoutComments + " spreadsheets " + files.size() + " without comments: " + arquivosErrados);
        }
    }

    /**
     * @param path path
     * @return list of the archives
     * @throws IOException error of IO
     */
    private List<URL> getFiles(String path) throws IOException {
        URL testInputURL = this.getClass().getClassLoader().getResource(path);
        return URLReaderFactory.getFileReader(testInputURL).getFiles(testInputURL, ".*xls");
    }

    /**
     * @param file arquivo
     * @return true if the archive has an sheet named NExec_@Doc
     * @throws IOException if the archive doesn't exists
     */
    private boolean hasComments(URL file) throws IOException {
        HSSFWorkbook spreadsheet = new HSSFWorkbook(file.openStream());
        return !(spreadsheet.getSheet(this.documentationSheet) == null);
    }

    /**
     * the SHEET to be set
     * 
     * @param documentationSheet documentationSheet
     */
    protected void setDocumentationSheet(String documentationSheet) {
        this.documentationSheet = documentationSheet;
    }

}
